#!/usr/bin/env python
# coding=utf-8

import base64
import getpass
import pprint
import pickle
import random
import string
import sys

def jiami(key):
	bytesstr = key.encode(encoding="utf-8")
	encodestr = base64.b64encode(bytesstr)
	obj = encodestr.decode()
	with open('mainPass.pass','wb') as f:
		pickle.dump(obj,f)	

def change_main_password():
	choice = input("手动输入密码/自动生成密码（y/n）：")
	if choice == 'y':
		key01 = getpass.getpass("请输入新的主密码：")
		key02 = getpass.getpass("请再输入一次新密码：")
		if key01 == key02:
			jiami(key01)
			print("密码修改成功！")
		else:
			print("两次密码不一致！")
	else :
		lenth = int(input("请输入你想要的密码长度："))
		passwd = []
		for i in range(lenth):
			i = random.choice(string.ascii_letters + string.digits + "~!@#$%^&*()_+")
			passwd.append(i)
		auto_password = ''.join(passwd)
		print("新密码变更为：" + auto_password)
		confirm = input("确认修改（y/n）：")
		if confirm == 'y':
			jiami(auto_password)
			print("密码修改成功！")
		else:
			change_main_password()

def jiemi(encodestr):
	decodestr = base64.b64decode(encodestr)
	key = decodestr.decode()
	return key

def open_data():
	try:
		with open("database.pass",'rb') as f:
			return pickle.load(f)
	except Exception as err:
		return False

def save_data(obj):
	with open("database.pass",'wb') as f:
		pickle.dump(obj,f)

class PassWord(dict):
	def __init__(self, passtype, title, user, password, url, remark):
		self.passtype = passtype
		self.title = title
		self[title] = {'user':user, 'passowrd':password, 'url':url, 'remark':remark}

	def password_data(self):
		pass_data = open_data() if open_data() else {}
		if self.passtype not in pass_data:
			pass_data[self.passtype] = {}
		if not pass_data:
			pass_data[self.passtype] = {}
			pass_data[self.passtype][self.title] = self[self.title]
		pass_data[self.passtype][self.title] = self[self.title]
		return pass_data	

	@classmethod
	def get_item(cls):
		cls.item = ['title', 'user', 'password', 'url', 'remark']
		return cls.item

	

"""
class WebPassWord(PassWord):
		def __init__(self, passtype, title, user, password, url):
			super().__init__(title, user, password, url)
			self.url = url
		@classmethod
		def get_item(self):
			return ['title', 'user', 'password', 'url']

class ServerPassWord(PassWord):
		def __init__(self, passtype, title, user, password, ip):
			super().__init__(title, user, password, ip)
			self.ip = ip
		@classmethod
		def get_item(self):
			return ['title', 'user', 'password', 'ip']
"""		

def read_password_information():
	pass_info = open_data()
	return pass_info

def write_password_information(passtype, **kwargs):
	pass_data = PassWord(passtype, **kwargs).password_data()
	save_data(pass_data)
	return True

def add_record(categroy):
	pass_info = {}
	for i in PassWord.get_item():
		pass_info[i] = input(i + ":")
	status = write_password_information(passtype=categroy, **pass_info)
	if status is False:
		print("Saving......Failed!")
	print("Saving......OK!")

def main():
	data = read_password_information()
	user_choice = input("""
	a、全部密码信息，c、修改主密码，
	d、删除密码记录，o、添加密码纪录，
	q、退出，s、查找。
	请选择：""")
	"""
	if user_choice == '1':
		pprint.pprint(data['web'])
	elif user_choice == '1.1':
		pass_info = {}
		for i in WebPassWord.get_item():
			pass_info[i] = input(i + ":")
		status = write_password_information(passtype='web', **pass_info)
		if status is False:
			print("Saving......Failed!")
		print("Saving......OK!")
	elif user_choice == '2':
		pprint.pprint(data['server'])
	elif user_choice == '2.1':
		pass_info = {}
		for i in ServerPassWord.get_item():
			pass_info[i] = input(i + ":")
		status = write_password_information(passtype='server', **pass_info)
		if status is False:
			print("Saving......Failed!")
		print("Saving......OK!")
	"""
	if user_choice == 'a':
		pprint.pprint(data)

	elif user_choice == 'c':
		old_passwd = getpass.getpass("请输入旧密码：")
		with open('mainPass.pass','rb') as f:
			mainpassword = pickle.load(f)
		main_password = jiemi(mainpassword)
		if main_password == old_passwd:
			change_main_password()
		else:
			print("旧密码输入错误")

	elif user_choice == 'd':
		del_passtype = input("请输入密码类别：")
		choice = input("是否直接删除此密码类别（y/n）：")
		if choice == 'y':
			data.pop(del_passtype)
			save_data(data)
			if del_passtype in data:
				print("删除失败。")
			else:
				print("删除成功。")
		elif choice == 'n':
			del_title = input("请输入要删除的密码标题：")
			data[del_passtype].pop(del_title)
			save_data(data)
			if del_title not in data[del_passtype]:
				print("删除成功。")
			else:
				print("删除失败。")

	elif user_choice == 'o':
		categroy = input("请输入你要创建或修改的密码类别:")
		add_record(categroy)

	elif user_choice == 'q':
		sys.exit(0)

	elif user_choice == 's':
		keyword01 = input("请输入要查找的密码类别:")
		keyword02 = input("请输入要查找的密码标题:")
		print(data[keyword01][keyword02])

	else:
		sys.exit(123)


if __name__ == '__main__':
	count = 0
	with open('mainPass.pass','rb') as f:
		mainpassword = pickle.load(f)
	main_password = jiemi(mainpassword)
	while count < 3:
		input_password = getpass.getpass("请输入密码：")
		if main_password == input_password:
			while True:
				main()
		else:
			count += 1
			print("密码错误，你有3次机会尝试！")
			continue
	else:
		print("密码输错3次，退出程序。")